<?php
Class  Model 
{
	public $db='';
	private $field='';
	private $page='';
	function __construct()
	{
		$this->dbinit();
		
		
	}
	
	public function dbinit()
	{
	   static $_db;
	   if(empty($_db))
	   {
		$this->db = $_db= new mysqlDB(C('db_host'), C('db_user'), C('db_pass'), C('db_name'));
		//$db_host = $db_user = $db_pass = $db_name = NULL;
	   }
	   else 
	   {
	   $this->db=$_db;
	   }
		
	}
	public function getCfg($key='')
	{
		if($key)
		{
			$sql="SELECT op_value FROM ".$this->table('options')." WHERE op_key='".$key."'";
			$arr=$this->getOne($sql);
				
		}
		else
		{
			$sql="SELECT op_value,op_key FROM ".$this->table('options')." WHERE op_key='wap_support' ";
			$arr=array();
			$res=$this->getAll($sql);
			if(count($res)>0)
			{
				foreach($res as $k=>$v)
				{
					$arr[$v['op_key']]=$v['op_value'];
				}
			}
		}
		C($arr);
		return $arr;
	}
	public function getAccessToken()
	{
		
		$path = ROOT_PATH."Qiaqia/Json/access_token.json";
		$data = json_decode(file_get_contents($path), true);
// 		var_dump($data);
		
		if(empty($data['access_token']) || $data['expire_time'] < yf_time())
		{
			$sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appid' OR op_key='appsecret' order by id asc";
			$temp = $this->getCol($sql);
			$app['appid'] = $temp[0];
			$app['appsecret'] = $temp[1];
			$new_info = Ctrl("weixin")->getToken($app['appid'], $app['appsecret']);
			$info['access_token'] = $new_info['access_token'];
			$info['expire_time'] = yf_time() + 1500;
 			$fp = fopen($path, "w");
 			fwrite($fp, json_encode($info));
 			fclose($fp);
			return $new_info['access_token'];
		}
		else 
		{
			Ctrl("weixin")->setToken($data['access_token']);
			return $data['access_token'];
		}
	}
	
	public function getAccessTokenCar()
	{
	
	    $path = ROOT_PATH."Qiaqia/Json/access_token_car.json";
	    $data = json_decode(file_get_contents($path), true);
	    if(empty($data['access_token']) || $data['expire_time'] < yf_time())
	    {
// 	        $sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appid' OR op_key='appsecret' order by id asc";
// 	        $temp = $this->getCol($sql);
	        $app['appid'] = "wx574f8bbb1864b332";
	        $app['appsecret'] = "706d17ca615cf2bbc75f6bd66e4bc685";
// 	        echo "aa";
	        $new_info = Ctrl("weixin")->getToken($app['appid'], $app['appsecret']);
	        $info['access_token'] = $new_info['access_token'];
	        $info['expire_time'] = yf_time() + 1500;
	        $fp = fopen($path, "w");
	        fwrite($fp, json_encode($info));
	        fclose($fp);
	        return $new_info['access_token'];
	    }
	    else
	    {
	        
	        Ctrl("weixin")->setToken($data['access_token']);
	        return $data['access_token'];
	    }
	}
	
	public function getAccessTokenJsCar()
	{
	
	    $path = ROOT_PATH."Qiaqia/Json/access_token_jscar.json";
	    $data = json_decode(file_get_contents($path), true);
	    if(empty($data['access_token']) || $data['expire_time'] < yf_time())
	    {
	        // 	        $sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appid' OR op_key='appsecret' order by id asc";
	        // 	        $temp = $this->getCol($sql);
	        $app['appid'] = "wx3164e1b26e094aeb";
	        $app['appsecret'] = "8eaf0440ce67bd2f089b788b273a06d1";
	        // 	        echo "aa";
	        $new_info = Ctrl("weixin")->getToken($app['appid'], $app['appsecret']);
	        $info['access_token'] = $new_info['access_token'];
	        $info['expire_time'] = yf_time() + 1500;
	        $fp = fopen($path, "w");
	        fwrite($fp, json_encode($info));
	        fclose($fp);
	        return $new_info['access_token'];
	    }
	    else
	    {
	         
	        Ctrl("weixin")->setToken($data['access_token']);
	        return $data['access_token'];
	    }
	}
	
	public function getAccessToken2()
	{
	
		
			$sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appid' OR op_key='appsecret' order by id asc";
			$temp = $this->getCol($sql);
			$app['appid'] = $temp[0];
			$app['appsecret'] = $temp[1];
			$new_info = Ctrl("weixin")->getToken($app['appid'], $app['appsecret']);
// 			$info['access_token'] = $new_info['access_token'];
// 			$info['expire_time'] = yf_time() + 1500;
// 			$fp = fopen($path, "w");
// 			fwrite($fp, json_encode($info));
// 			fclose($fp);
//             echo $new_info['access_token'];
			return $new_info['access_token'];
		
	}
	
	function del($cfg=array())
	{
		$t=$cfg['table'];
		unset($cfg['table']);
		$where=" WHERE 1=1 AND ";
		$logic=" AND ";
		foreach($cfg as $k=>$v)
		{
		   if(is_array($v))
			{
				$where.="".$k." in (".implode(',',$v).")".$logic;
			}
			else 
			{
			     $where.=" ".$k."='".$v."'".$logic;
			}
		}
		
		$where=$where."1=1";
		
		
		$sql="DELETE FROM ".$this->table($t).$where;
		
		$res=$this->query($sql);
		
		return $res;
	}
	public function update($info,$cfg)
	{
		if($cfg['id'])
		{
		
			foreach($info as $k=>$v)
			{
		
				$where.=" $k='$v',";
		
		
			}
				
			$where=substr($where,0,strlen($where)-1);
		
			$sql="UPDATE ".$this->table($cfg['table'])." SET ".$where." WHERE id='".$cfg['id']."'";
			return $res=$this->query($sql);
		}
	}
	public function insert($info,$table)
	{

		foreach($info as $k=>$v)
		{
			if($v!='')
			{
				$field.="$k,";
		
		
				$value.="'$v',";
					
			}
		}
			
			
		$field=substr($field,0,strlen($field)-1);
		$value=substr($value,0,strlen($value)-1);
			
		$sql="INSERT INTO ".$this->table($table)." (".$field.") VALUES(".$value.")";
		
		if(!$res=$this->query($sql))
		{
			return false;
		}
		else 
		{
			return $this->insert_id();
		}
	}
	//返回插入的id
	public function insert_id()
	{
		return $this->db->insert_id();
	}
	public function query($sql)
	{
		return $this->db->query($sql);
	}
	public function create_link($page_count,$curpage=1)
	{
		
		return $this->db->create_link($page_count,$curpage);
	}
	
	public function getpagelink()
	{
		return $this->db->page_link;
	}
	public function show_page($sql,$page=1,$page_size=10,$cfg=array(),$count_sql='')
	{
	
		$count_sql=$count_sql==''?'SELECT count(*) ':$count_sql;
		$from_index=strripos($sql,'FROM');
		$c_sql=$count_sql.substr($sql,$from_index);
		$data=array();
		$num=$this->db->getOne($c_sql);
		$data['count']=$num;
		if($num>0)
		{
			if(GROUP_NAME=='Home')
			{
				$cfg['rewrite']=REWRITE;
			}
			$page=new Page($page,$num,$page_size,$cfg);
			if(GROUP_NAME=='Home'&&DEFAULT_LANG=='en_us')
			{
				$page->set_lang(array('first_page'=>'First','next_page'=>'Next','pre_page'=>'Pre','last_page'=>'Last',));
			}
			
			
			
			
			$page->create_arr();
			$sql=$sql.' LIMIT '.$page->select_from.$page->select_limit;
			$data['result']=$this->db->getAll($sql);
			$data['page']=$page->html_page();
		}
		return $data;
	}
	

	public function get_page($field,$from,$where='',$page=1,$page_size='10')
	{
		
		return $this->db->get_page($field,$from,$where,$page,$page_size);
       
	}
	public function get_page2($field,$from,$where='',$page=1,$page_size='10')
	{
		
		return $this->db->get_page2($field,$from,$where,$page,$page_size);
       
	}
	
	public function table($table_name)
	{
		
		$table=C('prefix').$table_name;
		
		return $table ;
		
	}
	
	public function getOne($sql)
	{
		$result=$this->db->getOne($sql);
		return $result;
	}
	
	public function getAll($sql)
	{
		$result=$this->db->getAll($sql);
		return $result;
	}
	public function getCol($sql)
	{
		$result=$this->db->getCol($sql);
		return $result;
	}
	public function getRow($sql)
	{
		$result=$this->db->getRow($sql);
		return $result;
	}
	
	
	/**
	 * 获取jsdk的参数
	 * @author yf
	 */
	public function get_jsdk_card($signPackage,$cardList)
	{
	    $sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appid'";
	    $appid = $this->getOne($sql);
	   
	    $sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appsecret'";
	    $appSecret = $this->getOne($sql);
	    $path = ROOT_PATH."Qiaqia/Json/jsapi_ticket_card.json";
	    
	    $data = json_decode(file_get_contents($path), true);
	    
	    if(empty($data['jsapi_ticket']) || $data['expire_time'] < yf_time())
	    {
	        
	        $access_token = $this->getAccessToken();
	        $new_info = Ctrl("weixin")->getCardapiTicket($access_token);
	        $info['jsapi_ticket'] = $new_info['ticket'];
	        $info['expire_time'] = yf_time() + 1500;
	        $fp = fopen($path, "w");
	        fwrite($fp, json_encode($info));
	        fclose($fp);
	        $api_ticket = $new_info['ticket'];
	    }
	    else
	    {
	        $api_ticket = $data['jsapi_ticket'];
	    }
	    $timestamp = yf_time();
// 	    $nonceStr = $this->createNonceStr();
	    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
// 	    $cardId = "plHTpwmlhQqJ_6itfucIAlIcADaI";

// 	   echo $string2."<br>";
	   
// 	   echo $timestamp."<br>";
// 	   echo $nonceStr."<br>";
// 	   echo $jsapi_ticket."<br>";
// 	   echo $cardId."<br>";
// 	   echo $signatureCard;
// 	    $timestamp = $signPackage['timestamp'];
// 	    $nonceStr = $signPackage['nonceStr'];
	    
	    
// 	    $arrays = array($nonceStr,$timestamp,$cardId,$api_ticket);
	    
	    foreach ($cardList as $k=>$v)
	    {
	        $cardId = $v['cardId'];
    	    $arrays = array($appSecret,$timestamp,$cardId);
    	    sort($arrays , SORT_STRING);
    // 	    $string = "$timestamp$nonceStr$api_ticket$cardId";
    	    $string = implode($arrays);
    	    $signatureCard = sha1($string);
    // 	    $signatureCard = sha1($string);
    	    $cardSignature = '{"code": "", "openid": "","timestamp":"'.$timestamp.'","signature":"'.$signatureCard.'"}';
    // 	    $cardSignature = '{"code": "", "openid": "","timestamp":"'.$timestamp.'","nonceStr":"'.$nonceStr.'","signature":"'.$signatureCard.'"}';
//     	    $signPackage['cardId'] = $cardId;
//     	    $signPackage['cardSignature'] = $cardSignature;
    	    $cardList[$k]['cardSignature'] = $cardSignature;
	    }
	    
// 	    var_dump($cardList);
// 	    exit;
	    $signPackage['cardList'] = $cardList;
// 	    echo "卡券id:".$signPackage['cardId']."<br>";
// 	    echo "cardext:".$signPackage['cardSignature']."<br>";
// 	    echo "timestamp:".$timestamp."<br>";
// 	    echo "nonceStr:".$nonceStr."<br>";
// 	    echo "api_ticket:".$api_ticket."<br>";
// 	    echo "signature:".$signatureCard."<br>";
	    
// 	    echo "string:".$string."<br>";
// 	    echo $signatureCard;
	    
// 	    $signatureCard = $this->getJsSign($appSecret,$timestamp,$cardId);
	    
// 	    $signPackage = array(
// 	        "appId"     => $appid,
// 	        "nonceStr"  => $nonceStr,
// 	        "timestamp" => $timestamp,
// 	        "url"       => $url,
// 	        "signature" => $signature,
// 	        "rawString" => $string,
// 	        "cardId"     => $cardId,
// 	        "cardSignature"=>"{'timestamp':'$timestamp','nonceStr':'$nonceStr','signature':'$signatureCard'}"
// 	    );
	    
	    return $signPackage;
	}
	
	
	/**
	 * 获取jsdk的参数
	 * @author yf
	 */
	public function build_jsdk_card2($cardList)
	{
	    $sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appid'";
	    $appid = $this->getOne($sql);
	
	    $sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appsecret'";
	    $appSecret = $this->getOne($sql);
	    $path = ROOT_PATH."Qiaqia/Json/jsapi_ticket_card.json";
	
	    $data = json_decode(file_get_contents($path), true);
	
	    if(empty($data['jsapi_ticket']) || $data['expire_time'] < yf_time())
	    {
	
	        $access_token = $this->getAccessToken();
	        $new_info = Ctrl("weixin")->getCardapiTicket($access_token);
	        $info['jsapi_ticket'] = $new_info['ticket'];
	        $info['expire_time'] = yf_time() + 1500;
	        $fp = fopen($path, "w");
	        fwrite($fp, json_encode($info));
	        fclose($fp);
	        $api_ticket = $new_info['ticket'];
	    }
	    else
	    {
	        $api_ticket = $data['jsapi_ticket'];
	    }
	    $timestamp = yf_time();
	
	    $cards = array();
	
	    foreach ($cardList as $k=>$v)
	    {
	        $card = array();
	         
	        $cardId = $v['cardId'];
	        $arrays = array($appSecret,$timestamp,$cardId);
	        sort($arrays , SORT_STRING);
	        	
	        $string = implode($arrays);
	        $signatureCard = sha1($string);
	
	        $cardSignature = '{"code": "", "openid": "","timestamp":"'.$timestamp.'","signature":"'.$signatureCard.'"}';
	        	
	        $card['cardId'] = $cardId;
	        $card['cardExt'] = $cardSignature;
	
	        $cards[] = $card;
	    }
	
	
	     
	
	
	    return $cards;
	}
	
	/**
	 * 获取jsdk的参数
	 * @author yf
	 */
	public function build_jsdk_card($cardList)
	{
// 	    $sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appid'";
// 	    $appid = $this->getOne($sql);
	
// 	    $sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appsecret'";
// 	    $appSecret = $this->getOne($sql);
	    $path = ROOT_PATH."Qiaqia/Json/jsapi_ticket_card.json";
	     
	    $data = json_decode(file_get_contents($path), true);
	     
	    if(empty($data['jsapi_ticket']) || $data['expire_time'] < yf_time())
	    {
	         
	        $access_token = $this->getAccessToken();
	        $new_info = Ctrl("weixin")->getCardapiTicket($access_token);
	        $info['jsapi_ticket'] = $new_info['ticket'];
	        $info['expire_time'] = yf_time() + 1500;
	        $fp = fopen($path, "w");
	        fwrite($fp, json_encode($info));
	        fclose($fp);
	        $api_ticket = $new_info['ticket'];
	    }
	    else
	    {
	        $api_ticket = $data['jsapi_ticket'];
	    }
	    $timestamp = yf_time();
	   
	    $cards = array();
	     
	    foreach ($cardList as $k=>$v)
	    {
	        $card = array();
	    
    	    $cardId = $v['cardId'];
    	    $arrays = array($api_ticket,$timestamp,$cardId);
    	    sort($arrays , SORT_STRING);
    	    
    	    $string = implode($arrays);
    	    $signatureCard = sha1($string);
    
    	    $cardSignature = '{"code": "", "openid": "","timestamp":"'.$timestamp.'","signature":"'.$signatureCard.'"}';
    	    
    	    $card['cardId'] = $cardId;
    	    $card['cardExt'] = $cardSignature;
    	   
    	    $cards[] = $card;
	    }
	     

	  

		  
		    return $cards;
		}
	
		
		
		/**
		 * 获取jsdk的参数
		 * @author yf
		 */
		public function build_jsdk_card_car($cardList)
		{
		    
		    $path = ROOT_PATH."Qiaqia/Json/jsapi_ticket_card_car.json";
		
		    $data = json_decode(file_get_contents($path), true);
		
		    if(empty($data['jsapi_ticket']) || $data['expire_time'] < yf_time())
		    {
		
		        $access_token = $this->getAccessTokenJsCar();
		        $new_info = Ctrl("weixin")->getCardapiTicket($access_token);
		        $info['jsapi_ticket'] = $new_info['ticket'];
		        $info['expire_time'] = yf_time() + 1500;
		        $fp = fopen($path, "w");
		        fwrite($fp, json_encode($info));
		        fclose($fp);
		        $api_ticket = $new_info['ticket'];
		    }
		    else
		    {
		        $api_ticket = $data['jsapi_ticket'];
		    }
		    $timestamp = yf_time();
		
		    $cards = array();
		
		    foreach ($cardList as $k=>$v)
		    {
		        $card = array();
		         
		        $cardId = $v['cardId'];
		        $arrays = array($api_ticket,$timestamp,$cardId);
		        sort($arrays , SORT_STRING);
		        	
		        $string = implode($arrays);
		        $signatureCard = sha1($string);
		
		        $cardSignature = '{"code": "", "openid": "","timestamp":"'.$timestamp.'","signature":"'.$signatureCard.'"}';
		        	
		        $card['cardId'] = $cardId;
		        $card['cardExt'] = $cardSignature;
		
		        $cards[] = $card;
		    }
		
		
		     
		
		
		    return $cards;
		}
		
	
	function getJsSign($appSecret,$timestamp='', $cardId='', $code=''){
	    if(!empty($code))
	    {
	        $arrays = array($appSecret,$timestamp,$cardId,$code);
	    }else
	    {
	        $arrays = array($appSecret,$timestamp,$cardId);
	    }
	    sort($arrays , SORT_STRING);
	    $string = sha1(implode($arrays));
	    return $string;
	}
	
	/**
	 * 获取jsdk的参数
	 * @author yf
	 */
	public function get_jsdk_car()
	{
		//$sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appid'";
		$appid = "wx3164e1b26e094aeb";
		
		$path = ROOT_PATH."/Qiaqia/Json/jsapi_ticket_car.json";
		$data = json_decode(file_get_contents($path), true);
		
		if(empty($data['jsapi_ticket']) || $data['expire_time'] < yf_time())
		{
			$access_token = $this->getAccessTokenJsCar();
			$new_info = Ctrl("weixin")->getJsapiTicket($access_token);
			$info['jsapi_ticket'] = $new_info['ticket'];
			$info['expire_time'] = yf_time() + 1500;
			$fp = fopen($path, "w");
			fwrite($fp, json_encode($info));
			fclose($fp);
			$jsapi_ticket = $new_info['ticket'];
		}
		else 
		{
			$jsapi_ticket = $data['jsapi_ticket'];
		}
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		$timestamp = yf_time();
		$nonceStr = $this->createNonceStr();
		
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
		
		$signature = sha1($string);
// 		echo $string."<br>";
// 		echo $signature;
		$signPackage = array(
				"appId"     => $appid,
				"nonceStr"  => $nonceStr,
				"timestamp" => $timestamp,
				"url"       => $url,
				"signature" => $signature,
				"rawString" => $string
		);
		return $signPackage;
	}
	
	
	
	public function get_jsdk()
	{
	    $sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appid'";
// 	    $appid = "wx3164e1b26e094aeb";
	    $appid = $this->getOne($sql);
	    $path = ROOT_PATH."/Qiaqia/Json/jsapi_ticket.json";
	    $data = json_decode(file_get_contents($path), true);
	   
	    if(empty($data['jsapi_ticket']) || $data['expire_time'] < yf_time())
// 	    if(TRUE)
	    {
	        $access_token = $this->getAccessToken();
	       
	        $new_info = Ctrl("weixin")->getJsapiTicket($access_token);
	        $info['jsapi_ticket'] = $new_info['ticket'];
	        $info['expire_time'] = yf_time() + 1500;
	        $fp = fopen($path, "w");
	        fwrite($fp, json_encode($info));
	        fclose($fp);
	        $jsapi_ticket = $new_info['ticket'];
	    }
	    else
	    {
	        $jsapi_ticket = $data['jsapi_ticket'];
	    }
	    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	    $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	    $timestamp = yf_time();
	    $nonceStr = $this->createNonceStr();
	
	    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
	    $string = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
	
	    $signature = sha1($string);
	    // 		echo $string."<br>";
	    // 		echo $signature;
	    $signPackage = array(
	        "appId"     => $appid,
	        "nonceStr"  => $nonceStr,
	        "timestamp" => $timestamp,
	        "url"       => $url,
	        "signature" => $signature,
	        "rawString" => $string
	    );
	    return $signPackage;
	}
	
	
	/**
	 * jsdk获取字段
	 * @param number $length
	 * @return string
	 */
	private function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}
	
	/**
	 * 写入数据库(导入excel)
	 * @param unknown $table
	 * @param unknown $table_name
	 * @param unknown $data
	 */
	public function entry_forms($table, $table_name, $data)
	{
		$sql = "insert into ".$this->table($table_name)." (".$table.") values (".$data.")";
		return $this->query($sql);
	}
	
	
}